<template>
  <div :class="$style.wrapper">
    <el-table
      highlight-current-row
      border
      stripe
      v-loading="loading"
      @selection-change="onSelectChange"
      :data="value"
      :height="height"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <template v-for="column in _columns">
        <el-table-column
          :label="column.title"
          :prop="column.key"
          :type="column.type"
          :align="column.align"
          :width="column.width"
          :fixed="column.fixed"
          :sortable="column.sortable"
          :min-width="column.minWidth"
          :selectable="column.selectable"
          :class-name="$style.tdCell"
        >
          <template
            v-slot="scope"
            v-if="column.type !== 'index' && column.type !== 'selection'"
          >
            <slot v-bind="scope" :name="column.key">
              <span>{{ scope.row[column.key] }}</span>
            </slot>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <div v-if="!readOnly" :class="$style.footer">
      <div :class="$style.hdDivButton">
        <el-button type="primary" @click="add">添加</el-button>
        <el-button :disabled="disabled" @click="remove">删除</el-button>
      </div>
    </div>

    <el-dialog
      :title="label"
      :close-on-click-modal="false"
      :center="true"
      :width="width"
      draggable
      append-to-body
      v-model="visible"
    >
      <slot name="form">
        <el-form :model="editRecord" ref="subform" label-width="120px">
          <el-form-item
            v-for="field in _fields"
            :label="field.title"
            :prop="field.key"
          >
            <el-input v-model="editRecord[field.key]" size="mini" />
          </el-form-item>
        </el-form>
      </slot>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "HdTable",
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    /**
     * 字表的值，{key:value}的格式
     */
    value: {
      type: Array,
      default: () => [],
    },
    /**
     * 字表的字段属性
     */
    fields: {
      type: Array,
      default: () => [],
    },
    /**
     * 是否只读
     */
    readOnly: {
      type: Boolean,
      default: false,
    },
    /**
     * 标签名
     */
    label: {
      type: String,
      default: "",
    },
    /**
     * 自定义子表列属性,如[{dataIndex:'shuxingmingzi15',width:'120px'}],8.0.4及以后版本支持
     */
    columns: {
      type: Array,
      default: () => [],
    },
    /**
     * 某行是否可选
     * @since 8.0.11
     */
    showSelection: {
      type: Function,
      default: () => true,
    },
    /**
     * 删除时执行函数
     * @since 8.0.11
     */
    removeRows: {
      type: Function,
      default: () => true,
    },
    width: {
      type: String,
      default: "50%",
    },
    height: {
      type: [String, Number],
      default: "300",
    },
  },
  data() {
    return {
      selectedRowKeys: [],
      visible: false,
      editRecord: {}, // 待修改或编辑的记录
      attkeys: {}, // 附件组件的key,行编辑了就修改对应的附件key,强制更新附件列表
      loading: false,
      disabled: true,
    };
  },
  computed: {
    _columns() {
      return this.columns.map((a) => {
        if (["selection", "index"].includes(a.type)) {
          if (!a.align) a.align = "center";
          if (!a.title) a.title = "#";
        }
        return a;
      });
    },
    _fields() {
      if (this.fields.length > 0) return this.fields;
      return this._columns.filter((a) => !a.type);
    },
  },
  methods: {
    getDisplayVaule(field, text) {},
    add() {
      this.editRecord = {};
      this.fields.map((o) => (this.editRecord[o.key] = null));
      this.action = "add";
      this.visible = true;
    },
    edit(index) {
      this.editRecord = JSON.parse(JSON.stringify(this.fields));
      this.editRecord.forEach((item) => {
        // 把值放到字段信息fields里
        item.value = this.value[index][item.name];
      });
      this.visible = true;
      this.action = index;
    },
    save() {
      if (this.readOnly || !this.visible) {
        // 判断visable为false时，modal没有是为了防止快速重复点击确定
        this.visible = false;
        return;
      }
      this.$refs["subform"].validate((valid) => {
        const value = this.editRecord;
        const data = this.value || []; // 兼容初始值是null的情况
        if (this.action === "add") {
          // 新增
          data.push(value);
        }
        if (!isNaN(this.action)) {
          // 修改
          this.attkeys[this.action] = Math.random();
          data[this.action] = value;
        }
        this.$emit("addrow", value);
        /**
         * 动态表格值变化时触发
         * @property {Object} data 子表的值
         */
        this.$emit("change", [...data]);
        this.visible = false;
      });
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
      if (selectedRowKeys.length !== 0) this.disabled = false;
      else this.disabled = true;
      this.$emit("selectChange", selectedRowKeys);
    },
    remove(keys) {
      const _this = this;
      this.$confirm("您确定删除这项内容吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        _this.removeRows(_this.selectedRowKeys);
        _this.selectedRowKeys = [];
        _this.$emit("change", _this.value);
      });
    },
  },
};
</script>
<style module lang="scss">
.wrapper {
}
.hdDivButton {
  button {
    width: calc(50% - 5px);
  }
}
.tdCell {
  div span {
    padding-left: 5px;
  }
}
</style>
